package com.hundsun.cprs.yyt.web.action.system;

import com.hundsun.cprs.yyt.service.system.domain.TradeDay;
import com.hundsun.cprs.yyt.service.system.domain.TradeDayCurrent;
import com.hundsun.cprs.yyt.service.system.domain.query.TradeDayQuery;
import com.hundsun.cprs.yyt.service.system.enums.EnumCloseTradeStatus;
import com.hundsun.cprs.yyt.service.system.enums.EnumOpenTradeStatus;
import com.hundsun.cprs.yyt.service.system.service.TradeDayCurrentService;
import com.hundsun.cprs.yyt.service.system.service.TradeDayService;
import com.hundsun.cprs.yyt.util.DateUtil;
import com.hundsun.cprs.yyt.util.StringUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.eclp.biz.domain.user.UserAgent;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("system/tradeday/")
public class TradeDayAction extends BaseAction {

    @Autowired
    private TradeDayCurrentService tradeDayCurrentService;
    @Autowired
    private TradeDayService tradeDayService;

    @RequestMapping("list.htm")
    public String list(@ModelAttribute("query")TradeDayQuery query, ModelMap model){
        tradeDayService.queryByPage(query);
        model.addAttribute("enumOpenTradeStatus", EnumOpenTradeStatus.toMap());
        model.addAttribute("enumCloseTradeStatus", EnumCloseTradeStatus.toMap());
        return "system/trade/dayList";
    }

    @RequestMapping("add.htm")
    public String add(HttpServletRequest request, Model model) {
        int year = 0;
        String yearStr = request.getParameter("year");
        if (StringUtil.isBlank(yearStr)
                || Integer.parseInt(yearStr) == Calendar.getInstance().get(Calendar.YEAR)) {
            Calendar cal = Calendar.getInstance();
            year = cal.get(Calendar.YEAR);
            model.addAttribute("hasPrevious", false);
        } else {
            year = Integer.parseInt(yearStr);
            model.addAttribute("hasPrevious", true);
        }
        TradeDay tradeDay = new TradeDay();
        tradeDay.setYear(year);
        List<TradeDay> list = tradeDayService.getTradeDay(tradeDay);
        StringBuffer dates = new StringBuffer();
        for (TradeDay day : list) {
            dates.append(day.getDayStr()).append(",");
        }
        model.addAttribute("dates", dates.toString());
        model.addAttribute("year", year);
        return "system/trade/list";
    }

    @RequestMapping("edit.htm")
    public String edit(HttpServletRequest request,ModelMap model) {
        String datesStr = request.getParameter("dates");
        String year = request.getParameter("year");
        if (StringUtil.isBlank(year) || !NumberUtils.isDigits(year)) {
            return error(model, "参数错误");
        }

        List<Date> list = new ArrayList<Date>();
        if (StringUtil.isNotBlank(datesStr)) {
            String[] dates = datesStr.split(",");
            TradeDayCurrent current = tradeDayCurrentService.getCurrentTradeDay();
            Date nextTradeDay = current.getNextTradeDay();
            Date curretnTradeDay = current.getCurrentTradeDay();
            Date lastTradeDay = current.getLastTradeDay();
            Calendar cal = Calendar.getInstance();
            cal.setTime(nextTradeDay);
            int currentYear = cal.get(Calendar.YEAR);
            boolean isCurrentYear = false;
            // 判断是否修改今年的交易日
            if (Integer.parseInt(year) == currentYear) {
                isCurrentYear = true;
            }
            boolean isCancel = true;
            boolean isCurrentCancel = true;
            for (int i = 0; i < dates.length; i++) {
                if (StringUtil.isBlank(dates[i]))
                    continue;
                Long timeMills = Long.parseLong(dates[i]);
                cal.setTimeInMillis(timeMills);
                Date date = cal.getTime();
                if (date.before(nextTradeDay) && !date.equals(curretnTradeDay)
                        && !date.equals(lastTradeDay)) {
                    model.addAttribute("url", "/system/tradeday/list");
                    return error(model, "不允许修改下一清算日之前的时间");
                }
                if (date.equals(curretnTradeDay)) {
                    isCurrentCancel = false;
                    continue;
                }
                if (date.equals(nextTradeDay)) {
                    isCancel = false;
                    continue;
                }
                list.add(cal.getTime());
            }
            if (isCancel && isCurrentYear) {
                model.addAttribute("url", "/system/tradeday/list");
                return error(model, "不允许修改下一清算日");
            }

            Calendar today = Calendar.getInstance();
            today.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today
                    .get(Calendar.DAY_OF_MONTH), 0, 0, 0);
            today.set(Calendar.MILLISECOND, 0);
            boolean isSameYear = false;
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(curretnTradeDay);
            if (cal2.get(Calendar.YEAR) == Integer.parseInt(year))
                isSameYear = true;
            if (isCurrentCancel && !today.getTime().equals(curretnTradeDay) && isSameYear) {
                model.addAttribute("url", "/system/tradeday/list");
                return error(model, "admin.trade.tradeday.edit.curretnTradeDay");
            }
        }
        // 去除可能的重复
        HashSet<Date> h = new HashSet<Date>(list);
        list.clear();
        list.addAll(h);
        Collections.sort(list);
        tradeDayService.addTradeDay(list, Integer.parseInt(year));
        return success(model, "清算日设置成功","/system/tradeday/list");
    }

    @RequestMapping("list_current.htm")
    public String listCurrent(HttpServletRequest request, Model model) {
        TradeDayCurrent current = tradeDayCurrentService.getCurrentTradeDay();
        model.addAttribute("current", current);
        return "system/tradeday/list_current";
    }

    @RequestMapping("add_work_day.htm")
    public String addWorkDay(HttpServletRequest request, ModelMap model) throws ParseException {
        String startDateStr = request.getParameter("startDate");
        if (StringUtil.isBlank(startDateStr)) {
            return error(model, "参数错误");
        }
        try {
            Date startDate = DateUtil.convertStringToDate(startDateStr);
            tradeDayService.addWorkDay(startDate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(startDate);
            return success(model, "选取所有工作日成功","/system/tradeday/list");
        } catch (ParseException e) {
            log.error("TradeDayAction.addWorkDay():ParseException", e);
            return error(model, "时间解析出错");
        }

    }
}
